package com.wejoy.video.middle.station.data.service.system.impl;

import com.wejoy.video.middle.station.data.domain.system.SysResource;
import com.wejoy.video.middle.station.data.enums.dict.EnumStatus;
import com.wejoy.video.middle.station.data.enums.dict.EnumSysResourceType;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.wejoy.video.middle.station.data.mapper.system.ISysResourceMapper;
import com.wejoy.video.middle.station.data.service.common.IIdWorkerService;
import com.wejoy.video.middle.station.data.service.system.ISysResourceService;
import com.wejoy.video.middle.station.data.util.WJAssert;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统--权限表
 *
 * @author admin
 * @date 2021年10月20日 08:59:10
 */
@Service
public class SysResourceServiceImpl implements ISysResourceService {
    @Autowired
    private ISysResourceMapper sysResourceMapper;
    @Autowired
    private IIdWorkerService idWorkerService;

    @Override
    public void save(SysResource req, String operator) {
        req.setOperator(operator);
        if (StringUtils.isNotBlank(req.getIdentity())) {
            SysResource where = new SysResource();
            where.setIdentity(req.getIdentity());
            SysResource resourceDB = sysResourceMapper.getOne(where);
            if (resourceDB != null && !resourceDB.getId().equals(req.getId())) {
                throw new BusinessException("标识已存在！");
            }
        }
        if (null == req.getId()) {
            insertSelective(req);
        } else {
            updateSelectiveById(req);
        }
    }

    @Override
    public int insertSelective(SysResource req) {
        req.setId(idWorkerService.getNextId());
        req.setStatus(EnumStatus.NEW.getCode());
        checkStringLength(req, false);
        return sysResourceMapper.insertSelective(req);
    }

    @Override
    public int updateSelectiveById(SysResource sysResource) {
        WJAssert.notNull(sysResource, "入参对象不能为空");
        WJAssert.notNull(sysResource.getId(), "id参数错误");
        SysResource where = new SysResource();
        where.setId(sysResource.getId());
        return sysResourceMapper.updateSelective(sysResource, where);
    }

    @Override
    public int getCount(SysResource sysResource) {
        checkStringLength(sysResource, true);
        return sysResourceMapper.getCount(sysResource);
    }

    @Override
    public SysResource getOneById(Long id) {
        WJAssert.notNull(id, "id参数错误");
        SysResource where = new SysResource();
        where.setId(id);
        return sysResourceMapper.getOne(where);
    }

    @Override
    public List<SysResource> getList(SysResource sysResource) {
        checkStringLength(sysResource, true);
        return sysResourceMapper.getList(sysResource);
    }

    @Override
    public List<SysResource> getPageList(SysResource sysResource) {
        checkStringLength(sysResource, true);
        return sysResourceMapper.getPageList(sysResource);
    }

    @Override
    public void audit(Long id, String operator) {
        SysResource req = new SysResource();
        req.setId(id);
        req.setOperator(operator);
        req.setStatus(EnumStatus.AUDIT.getCode());
        updateSelectiveById(req);
    }

    @Override
    public void unaudit(Long id, String operator) {
        SysResource req = new SysResource();
        req.setId(id);
        req.setOperator(operator);
        req.setStatus(EnumStatus.NEW.getCode());
        updateSelectiveById(req);
    }

    @Override
    public void delete(Long id, String operator) {
        SysResource req = new SysResource();
        req.setId(id);
        req.setOperator(operator);
        req.setStatus(EnumStatus.DEL.getCode());
        updateSelectiveById(req);
    }

    /**
     * 获取目录分页数据
     *
     * @param sysResource
     * @return
     */
    @Override
    public List<SysResource> getPageTreeList(SysResource sysResource) {
        SysResource where = new SysResource();
        sysResource.setStatus(EnumStatus.NEW.getCode());
        List<SysResource> listDB = sysResourceMapper.getList(where);

        return sysResourceMapper.getPageList(sysResource)
                .stream().peek(item -> {
                    item.setLabel(item.getName());
                    item.setChildren(getChildrenTree(listDB, item.getId().toString()));
                }).collect(Collectors.toList());
    }

    /**
     * 获取资源树
     * 获取全部数据进行楼中楼
     *
     * @return
     */
    @Override
    public List<SysResource> getResourceTree() {
        SysResource sysResource = new SysResource();
        sysResource.setStatus(EnumStatus.NEW.getCode());
        List<SysResource> listDB = sysResourceMapper.getList(sysResource);

        List<SysResource> catalogueList = listDB.stream().filter(item -> {
            return item.getType().equals(EnumSysResourceType.CATALOGUE.getCode());
        }).sorted(Comparator.comparing(SysResource::getSort)).collect(Collectors.toList());

        return catalogueList.stream()
                .peek(item -> {
                    item.setLabel(item.getName());
                    item.setIcon("el-icon-folder-opened");
                    item.setChildren(getChildrenTree(listDB, item.getId().toString()));
                }).collect(Collectors.toList());
    }

    /**
     * 根据目录盖楼 格式（目录->菜单->按钮）
     *
     * @param listDB
     * @param parentId
     * @return
     */
    private List<SysResource> getChildrenTree(List<SysResource> listDB, String parentId) {
        return listDB.stream()
                .filter(item -> {
                    return parentId.equals(item.getParentId()) && EnumSysResourceType.MENU.getCode().equals(item.getType());
                }).peek(item -> {
                    item.setLabel(item.getName());
                    item.setIcon("el-icon-document");
                    List<SysResource> btnList = listDB.stream()
                            .filter(btnItem -> {
                                return btnItem.getParentId().equals(item.getId().toString()) && EnumSysResourceType.BUTTON.getCode().equals(btnItem.getType());
                            }).peek(btnItem -> {
                                btnItem.setLabel(btnItem.getName());
                            }).sorted(Comparator.comparing(SysResource::getSort)).collect(Collectors.toList());
                    item.setChildren(btnList);
                }).sorted(Comparator.comparing(SysResource::getSort)).collect(Collectors.toList());
    }

    /**
     * 参数校验注解默认使用的方法
     */
    private void checkStringLength(SysResource sysResource, boolean nullAble) {
        WJAssert.notNull(sysResource, "入参对象不能为空");
        WJAssert.limitMaxLength(sysResource.getName(), nullAble, 100, "菜单名称不合法!");
        WJAssert.limitMaxLength(sysResource.getUrl(), true, 200, "链接地址不合法!");
        WJAssert.limitMaxLength(sysResource.getParentId(), true, 32, "父菜单ID不合法!");
        WJAssert.limitMaxLength(sysResource.getIcon(), true, 200, "图标不合法!");
        WJAssert.limitMaxLength(sysResource.getIdentity(), nullAble, 255, "权限标识不合法!");
        WJAssert.limitMaxLength(sysResource.getOperator(), true, 50, "操作人不合法!");
        WJAssert.limitMaxLength(sysResource.getRemark(), true, 255, "备注不合法!");
        WJAssert.limitMaxLength(sysResource.getRootPath(), true, 255, "根路径,用.分隔不合法!");
    }
}
